<script setup lang="ts">
// 引入vue相关
import {nextTick, onMounted, reactive, ref, Ref, computed} from "vue";
// 引入element-plus组件
import {ElMessage, FormInstance} from "element-plus";
// 引入自定义弹框组件
import SysDialog from "@/components/dialog/SysDialog.vue";
// 引入弹框组件的Hooks封装属性和方法
import useDialog from "@/hooks/useDialog.ts";
// 弹框属性和方法
const {dialog, onShow, onClose, onConfirm} = useDialog()
// 获取全局实例
import useInstance from "@/hooks/useInstance.ts";
// 获取全局 global
const {global} = useInstance()

// 项目api
import {getProjectDocumentListApi} from "@/api/project";
import {ProjectDocument, ProjectDocumentListParam} from "@/api/project/type";

// 电控核价api
import {costPlanListParam, CostPricingPlanBatchCopyDto} from '@/api/costPricingPlan/type'
import {queryCostPlanListApi, deleteApi, updateStatusApi, batchUpdateStatusApi, exportCostPlanApi, batchCopyApi} from '@/api/costPricingPlan/index.ts'
import ArchiveSelector from "@/components/common/ArchiveSelector.vue";

// 引入图标
import {Plus, Search, Refresh, Delete, Check, Close, Download, CopyDocument} from '@element-plus/icons-vue';
// 引入格式化工具
import { formatPrice, formatNumber } from '@/utils/formatter';
// 引入vue-router
import {useRouter} from 'vue-router'
// 获取路由实例
const router = useRouter()

// 定义表单ref实例
const form = ref<FormInstance>()

//定义表单校验规则
const rules = {}

// 表格数据和总条数和表格高度和加载效果
const dataList = ref<any[]>([])  // 表格列表数据
const total = ref(0)  // 分页器总条数
const loading = ref(false)    // 表格加载效果
const tableHeight = ref(0)    // 表格内容高度

// 批量操作相关
const selectedRows = ref<any[]>([])
const tableRef = ref()

// 批量复制相关
const batchCopyVisible = ref(false)
const targetProjectSelectorVisible = ref(false)
const selectedTargetProject = ref<ProjectDocument | null>(null)

// 定义搜索表单数据
const searchForm = ref<costPlanListParam>({
  projectId: undefined,
  activate: undefined,
  page: 1,
  limit: 10,
})

// 项目选择器相关数据
const projectSelectorVisible = ref(false);
const selectedProject = ref<ProjectDocument | null>(null);



// 项目状态映射
const statusOptions = [
  {value: 0, label: '进行中'},
  {value: 1, label: '已完成'},
  {value: 2, label: '已暂停'},
  {value: 3, label: '已取消'}
];

// 项目选择器搜索字段配置
const projectSearchFields = [
  {label: '项目名称', prop: 'name', type: 'input' as const},
  {label: '项目编号', prop: 'code', type: 'input' as const},
  {label: '客户名称', prop: 'customer', type: 'input' as const},
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: statusOptions
  }
];

// 项目选择器表格列配置
const projectTableColumns = [
  {prop: 'name', label: '项目名称', width: 250},
  {prop: 'code', label: '项目编号', width: 250},
  {prop: 'customer', label: '客户名称', width: 250},
  {prop: 'manager', label: '项目经理', width: 200}
];


// 获取项目列表数据的API方法
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10
    }
    
    const res = await getProjectDocumentListApi(queryParams)
    return res
  } catch (error) {
    console.error('获取项目列表失败:', error)
    throw error
  }
}

// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project;
  console.log('选择的项目:', project);
  searchForm.value.projectId = project.id || 0;
  projectSelectorVisible.value = false;
};

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true;
};

// 导出数据
const handleExport = async () => {
  try {
    loading.value = true
    
    // 构建导出参数
    const exportParams = {
      ...searchForm.value,
      page: 1,
      limit: 999999  // 设置一个大数字，后端会重新设置为MAX_VALUE
    }

    const response = await exportCostPlanApi(exportParams)
    
    // 检查响应数据
    let blobData: Blob
    if (response && typeof response === 'object' && 'data' in response) {
      // HTTP拦截器返回完整的response对象，提取data字段
      blobData = (response as any).data
    } else if ((response as any) instanceof Blob) {
      // 直接是Blob数据
      blobData = response as Blob
    } else {
      console.error('导出响应格式错误:', response)
      ElMessage.error('导出数据格式错误')
      return
    }
    
    // 确保blobData是Blob类型
    if (!(blobData instanceof Blob)) {
      console.error('提取的数据不是Blob类型:', blobData)
      ElMessage.error('导出数据格式错误')
      return
    }
    
    // 检查blob大小
    if (blobData.size === 0) {
      ElMessage.error('导出文件为空')
      return
    }
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blobData)
    const link = document.createElement('a')
    link.href = url
    
    // 生成文件名
    const now = new Date()
    const timestamp = now.getFullYear() + 
      String(now.getMonth() + 1).padStart(2, '0') + 
      String(now.getDate()).padStart(2, '0') + '_' +
      String(now.getHours()).padStart(2, '0') + 
      String(now.getMinutes()).padStart(2, '0') + 
      String(now.getSeconds()).padStart(2, '0')
    
    link.download = `成本核价方案_${timestamp}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}



// 获取数据列表方法
const getDataList = async () => {
  loading.value = true
  isDataLoaded.value = false // 数据加载开始，设置标志位为false
  try {
    const res = await queryCostPlanListApi(searchForm.value)
    dataList.value = res.data.list
    total.value = res.data.total
    // 使用nextTick确保DOM更新完成后再设置标志位
    await nextTick()
    isDataLoaded.value = true // 数据加载完成，设置标志位为true
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  searchForm.value.page = 1
  getDataList()
}

// 搜索重置方法
const handleReset = () => {
  searchForm.value = {
    projectId: undefined,
    activate: undefined,
    page: 1,
    limit: 10
  }
  selectedProject.value = null
  getDataList()
}

// 修改核价单的状态
const updateStatus = reactive({
  id: undefined as number | undefined,
  activate: undefined as boolean | undefined
})

// 标志位：防止初始化时触发
const isDataLoaded = ref(false)

// 激活 失效
const activateChange = async (val: boolean, id: number) => {
  // 如果数据还没加载完成，不执行更新操作
  if (!isDataLoaded.value) return

  updateStatus.id = id
  updateStatus.activate = val
  try {
    await updateStatusApi({id, activate: val ? 1 : 0})
    ElMessage.success('操作成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}


// 分页变化
const handleCurrentChange = (page: number) => {
  searchForm.value.page = page
  getDataList()
}


// 每页条数变化
const handleSizeChange = (size: number) => {
  searchForm.value.limit = size
  searchForm.value.page = 1
  getDataList()
}


// 删除数据方法
const handleDelete = async (id: number) => {
  // 检查对应记录的状态
  const record = dataList.value.find(item => item.id === id)
  if (record && record.activate !== 1) {
    ElMessage.warning('该电控核价单已失效，不允许删除')
    return
  }
  
  try {
    const confirm = await global.$myConfirm('确定要删除该核价单吗，是否继续?');
    console.log('confirm:', confirm)
    if (!confirm) {
      return
    }
      await deleteApi(id)
      ElMessage.success('删除成功')
      getDataList()

  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 处理表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  // 检查选中的记录中是否有已失效的
  const invalidRecords = selectedRows.value.filter(item => item.activate !== 1)
  if (invalidRecords.length > 0) {
    ElMessage.warning(`选中的记录中有${invalidRecords.length}条已失效，不允许删除操作`)
    return
  }

  try {
    const confirm = await global.$myConfirm(`确定要删除选中的 ${selectedRows.value.length} 条数据吗？`)
    if (!confirm) {
      return
    }
    
    const ids = selectedRows.value.map(row => row.id).filter(id => id)
    // 这里需要后端提供批量删除API，暂时使用循环删除
    for (const id of ids) {
      await deleteApi(id)
    }
    ElMessage.success('批量删除成功')
    getDataList()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('批量删除失败')
  }
}

// 批量失效
const handleBatchDeactivate = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要失效的记录')
    return
  }
  
  try {
    const confirm = await global.$myConfirm(`确定要将选中的${selectedRows.value.length}条记录设为失效吗？`)
    if (!confirm) {
      return
    }
    
    const ids = selectedRows.value.map(row => row.id).filter(id => id)
    await batchUpdateStatusApi({ ids, activate: 0 })
    ElMessage.success('批量失效成功')
    getDataList()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    console.error('批量失效失败:', error)
    ElMessage.error('批量失效失败')
  }
}

// 批量生效
const handleBatchActivate = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要生效的记录')
    return
  }
  
  try {
    const confirm = await global.$myConfirm(`确定要将选中的${selectedRows.value.length}条记录设为生效吗？`)
    if (!confirm) {
      return
    }
    
    const ids = selectedRows.value.map(row => row.id).filter(id => id)
    await batchUpdateStatusApi({ ids, activate: 1 })
    ElMessage.success('批量生效成功')
    getDataList()
    // 清空选择
    tableRef.value?.clearSelection()
  } catch (error) {
    console.error('批量生效失败:', error)
    ElMessage.error('批量生效失败')
  }
}

// 打开批量复制弹窗
const openBatchCopyDialog = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要复制的记录')
    return
  }
  
  // 允许复制失效数据，复制后自动生效
  
  batchCopyVisible.value = true
}

// 关闭批量复制弹窗
const closeBatchCopyDialog = () => {
  batchCopyVisible.value = false
  selectedTargetProject.value = null
}

// 打开目标项目选择器
const openTargetProjectSelector = () => {
  targetProjectSelectorVisible.value = true
}

// 处理目标项目选择
const handleTargetProjectSelect = (project: ProjectDocument) => {
  selectedTargetProject.value = project
  console.log('选择的目标项目:', project)
}

// 确认批量复制
const confirmBatchCopy = async () => {
  if (!selectedTargetProject.value) {
    ElMessage.warning('请选择目标项目')
    return
  }
  
  try {
    await global.$myConfirm(`确定要将选中的${selectedRows.value.length}条成本核价方案复制到项目"${selectedTargetProject.value.name}"吗？`)
    
    const sourceIds = selectedRows.value.map(row => row.id).filter(id => id)
    await batchCopyApi({
      sourceIds,
      targetProjectId: selectedTargetProject.value.id!
    })
    
    ElMessage.success(`成功复制${sourceIds.length}条成本核价方案`)
    closeBatchCopyDialog()
    await getDataList()
    
    // 清空选中状态
    selectedRows.value = []
    tableRef.value?.clearSelection()
  } catch (error) {
    console.error('批量复制失败:', error)
    ElMessage.error('批量复制失败')
  }
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 删除本地格式化函数，使用统一的格式化工具

// 获取状态标签类型
const getStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'primary' // 进行中
    case 1:
      return 'success' // 已完成
    case 2:
      return 'warning' // 已暂停
    case 3:
      return 'danger'  // 已取消
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: number) => {
  const option = statusOptions.find(item => item.value === status)
  return option ? option.label : '-'
}

// 查看
const handleView = (id: number) => {
  router.push(`/costForm/${id}?mode=view`)
}

// 编辑
const handleEdit = (id: number) => {
  // 检查对应记录的状态
  const record = dataList.value.find(item => item.id === id)
  if (record && record.activate !== 1) {
    ElMessage.warning('该电控核价单已失效，不允许编辑')
    return
  }
  router.push(`/costForm/${id}`)
}

// 新增
const handleAdd = () => {
  router.push(`/costForm`)
}

// 页面加载时获取列表数据
onMounted(() => {
  // 设置表格高度
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
  // 获取数据列表
  getDataList()
})
</script>

<template>
  <div class="container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-wrapper">
        <!-- 搜索表单 -->
        <div class="search-form-section">
          <el-form :inline="true" ref="queryForm" class="demo-form-inline">
            <el-form-item label="项目信息">
              <el-input
                  :model-value="selectedProject ? selectedProject.name : ''"
                  placeholder="请选择项目"
                  readonly
                  class="selector-input"
              >
                <template #append>
                  <el-button @click="openProjectSelector" v-permission="['costPlan:view']">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                  v-model="searchForm.activate"
                  placeholder="是否生效"
                  clearable
                  filterable
                  style="width: 120px"
              >
                <el-option label="生效" :value="1" />
                <el-option label="失效" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item class="search-buttons">
              <el-button type="primary" @click="handleSearch" class="search-btn" v-permission="['costPlan:view']">
                <el-icon>
                  <Search />
                </el-icon>
                查询
              </el-button>
              <el-button @click="handleReset" class="reset-btn" v-permission="['costPlan:view']">
                <el-icon>
                  <Refresh />
                </el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="action-buttons-section">
          <div class="button-group primary-actions">
            <!-- 主要操作按钮 -->
          </div>

          <div class="button-group secondary-actions">
            <el-button type="success" @click="handleAdd" class="add-btn" v-permission="['costPlan:edit']">
              <el-icon>
                <Plus />
              </el-icon>
              新增
            </el-button>
            <el-button type="primary" @click="handleExport" class="export-btn" v-permission="['costPlan:view']">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
            <!-- <el-button type="primary" @click="openExportDialog" class="custom-export-btn">
              <el-icon><Setting /></el-icon>
              自定义导出
            </el-button> -->
            <el-button 
              type="danger" 
              @click="handleBatchDelete" 
              class="batch-delete-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['costPlan:edit']"
            >
              <el-icon><Delete /></el-icon>
              批量删除 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="warning" 
              @click="handleBatchDeactivate" 
              class="batch-deactivate-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['costPlan:edit']"
            >
              <el-icon><Close /></el-icon>
              批量失效 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="success" 
              @click="handleBatchActivate" 
              class="batch-activate-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['costPlan:edit']"
            >
              <el-icon><Check /></el-icon>
              批量生效 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
            <el-button 
              type="primary" 
              @click="openBatchCopyDialog" 
              class="batch-copy-btn"
              :disabled="selectedRows.length === 0"
              v-permission="['costPlan:edit']"
            >
              <el-icon><CopyDocument /></el-icon>
              批量复制 {{ selectedRows.length > 0 ? `(${selectedRows.length})` : '' }}
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 数据列表 -->
    <el-card class="list-card" shadow="never">
      <el-table
          ref="tableRef"
          v-loading="loading"
          :data="dataList"
          :height="tableHeight"
          element-loading-text="加载中..."
          element-loading-background="rgba(255, 255, 255, 0.7)"
          style="width: 100%"
          stripe
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column type="index" label="序号" min-width="60" align="center" show-overflow-tooltip />
        <el-table-column prop="activate" label="状态" min-width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.activate ? 'success' : 'danger'">
            {{ scope.row.activate ? '生效' : '失效' }}
          </el-tag>
        </template>
      </el-table-column>
        <el-table-column prop="projectName" label="项目名称" min-width="180" align="center" show-overflow-tooltip />
        <el-table-column prop="docType" label="类型" min-width="120" align="center" show-overflow-tooltip />

        <el-table-column prop="totalPrice" label="总价" min-width="150" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="price-value">{{ formatPrice(scope.row.totalPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.createName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span class="date-value">{{ formatDate(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateName" label="更新人" min-width="120" align="center" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.updateName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="350" align="center" fixed="right">
          <template #default="scope">
            <el-button type="info" plain size="small" @click="handleView(scope.row.id)" v-permission="['costPlan:view']">
              查看
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row.id)" :disabled="scope.row.activate !== 1" v-permission="['costPlan:edit']">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)" :disabled="scope.row.activate !== 1" v-permission="['costPlan:edit']">
              删除
            </el-button>
            <!-- <el-switch v-model="scope.row.activate"
                       class="ml-2"
                       inline-prompt
                       style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;margin-left: 15px"
                       active-text="生效"
                       inactive-text="失效"
                       :active-value="1"
                       :inactive-value="0"
                       @change="activateChange($event === 1,scope.row.id)" /> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="searchForm.page"
            v-model:page-size="searchForm.limit"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="prev, pager, next, jumper,->,sizes,total"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </el-card>

  </div>

  <!-- 项目选择器组件 -->
  <ArchiveSelector v-model="projectSelectorVisible"
                   title="选择项目"
                   :search-fields="projectSearchFields"
                   :table-columns="projectTableColumns"
                   :fetch-data-api="getProjectList"
                   :multiple="false"
                   @confirm="handleProjectSelect" />

  <!-- 批量复制弹窗 -->
  <el-dialog
    v-model="batchCopyVisible"
    title="批量复制成本核价方案"
    width="600px"
    :close-on-click-modal="false"
  >
    <div class="batch-copy-content">
      <el-alert
        title="提示"
        type="info"
        description="将选中的成本核价方案复制到指定的目标项目中，包含主数据、成本明细和额外项。"
        :closable="false"
        style="margin-bottom: 20px"
      />
      
      <div class="copy-info">
        <p><strong>选中记录数：</strong>{{ selectedRows.length }} 条</p>
        <p><strong>源项目：</strong>{{ selectedRows.map(row => row.projectName).filter((name, index, arr) => arr.indexOf(name) === index).join(', ') }}</p>
      </div>
      
      <el-form label-width="120px" style="margin-top: 20px">
        <el-form-item label="目标项目" required>
          <el-input
            :model-value="selectedTargetProject?.name || ''"
            placeholder="请选择目标项目"
            readonly
          >
            <template #append>
              <el-button @click="openTargetProjectSelector" v-permission="['costPlan:edit']">选择项目</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeBatchCopyDialog">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmBatchCopy"
          :disabled="!selectedTargetProject"
        >
          确认复制
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 目标项目选择器 -->
  <ArchiveSelector
    v-model="targetProjectSelectorVisible"
    title="选择目标项目"
    :fetch-data-api="getProjectList"
    :search-fields="projectSearchFields"
    :table-columns="projectTableColumns"
    @confirm="handleTargetProjectSelect"
  />

</template>

<style scoped lang="scss">
.cost-plan-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .search-card {
    margin-bottom: 20px;

    .action-buttons-section {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      margin-top: 15px;
      padding-top: 15px;
      border-top: 1px solid #ebeef5;

      .button-group {
        display: flex;
        gap: 8px;
        align-items: center;

        &.primary-actions {
          flex: 1;
          justify-content: flex-start;
        }

        &.secondary-actions {
          justify-content: flex-end;
        }
      }
    }
  }

  .list-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: right;
    }

    .price-value {
      color: #e6a23c;
      font-weight: bold;
    }

    .date-value {
      color: #606266;
    }
  }


}

#app .el-table .el-table__header-wrapper th {
  background-color: #DCDCDC;
  border-bottom: 1px solid #8B8B7A;
  border-right: 1px solid #8B8B7A;
}

input::-webkit-inner-spin-button,
input::-webkit-outer-spin-button {
  -webkit-appearance: none !important;
}
</style>
